/*
 * Copyright (c) 2015 Minshenglife. All rights reserved. Minshenglife
 * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.sentry.commons.crypto;

import com.sentry.commons.utils.Exceptions;

import java.security.GeneralSecurityException;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * 安全摘要算法
 * 
 * @author WuBo (wub1@minshenglife.com)
 *
 */
public class Hamc {
    
    static enum HmacAlg {

        SHA1("HmacSHA1"), SHA256("HmacSHA256"), SHA512("HmacSHA512"), MD5("HmacMD5");

        String value;

        private HmacAlg(String alg) {
            this.value = alg;
        }    
    }

    private Hamc() {}


    /**
     * hmacsha1 / hmacsha256 /hmacsha512的安全摘要算法
     * 
     * @param input
     * @param key
     * @param macType {@link HmacAlg}
     * @return
     */
    public static byte[] hmac(byte[] input, byte[] key, HmacAlg alg) {
        try {
            SecretKey secretKey = new SecretKeySpec(key, alg.value);
            Mac mac = Mac.getInstance(alg.value);
            mac.init(secretKey);
            return mac.doFinal(input);
        } catch (GeneralSecurityException e) {
            throw Exceptions.unchecked(e);
        }
    }
}
